﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using SmartSpace.Web;
using SmartSpace.Core;
using SmartSapce.ServiceLocation;

namespace SmartSpace.WebApp._console.page
{
    public partial class page_edit : System.Web.UI.Page
    {
        private Guid _pageId;

        protected void Page_Load(object sender, EventArgs e)
        {
            _pageId = Request.GetGuid("id");

            if (!IsPostBack)
            {
                ICoreService service = ServiceLocator.Get<ICoreService>();
                VirtualPage page = service.GetPage(SsSite.Current.Id, _pageId);
                if (page != null)
                {
                    _ctlEditCode.Text = page.Code;
                    _ctlEditCaption.Text = page.Caption;

                    _ctlEditCurTemplate.Text = page.Template.Caption;
                }
                else
                {
                    Response.Redirect("./page-list.aspx");
                }
            }
        }

        protected void _ctlBtnSave_Click(object sender, EventArgs e)
        {
            Guid curTemplateId = default(Guid);
            Guid templateId = Guid.Empty;
            if (!string.IsNullOrEmpty(_ctlSelTemplateId.Value))
            {
                templateId = new Guid(_ctlSelTemplateId.Value);
            }


            ICoreService service = ServiceLocator.Get<ICoreService>();
            VirtualPage page = service.GetPage(SsSite.Current.Id, _pageId);
            page.Code = _ctlEditCode.Text;
            page.Caption = _ctlEditCaption.Text;

            if (templateId != Guid.Empty)
            {
                curTemplateId = page.TemplateId;
                page.TemplateId = templateId;
            }
            if (service.SavePage(page))
            {
                if (templateId != Guid.Empty && templateId != curTemplateId)
                {
                    // 清除页面配置内容
                    Logger.Info(string.Format("delete content for page {0}[{1}]!", page.Caption, page.Id));
                    if (service.DeletePageContent(SsSite.Current.Id, page.Id).IsSuccess)
                    {
                        Logger.Info(string.Format("delete content for page {0}[{1}] success!", page.Caption, page.Id));
                    }
                    else
                    {
                        Logger.Error(string.Format("delete content for page {0}[{1}] failure!", page.Caption, page.Id));
                    }
                }

                Response.Redirect("./page-list.aspx");
            }
        }
    }
}